<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-04-04
 * Time: 20:31
 */

namespace App\Services\Impl;


use App\Common\Constant\Params;
use App\Models\MasterStatisticWeek;
use App\Models\MasterTradeLog;
use App\Models\Order;
use App\Models\OrderOffer;
use App\Services\IStatisticService;
use Carbon\Carbon;
use Illuminate\Support\Collection;

class StatisticServiceImpl implements IStatisticService
{
    public function lastThreeMonthBillList($master_id)
    {
        $bill_list = Collection::make([]);
        $time = Carbon::today();
        $lastThreeMonth = Carbon::today()->subMonths(3);
        while ($time->gt($lastThreeMonth)){
            $monday_time = $time->previous()->startOfWeek();
            $week_bill = $this->weekBill($master_id,$monday_time->timestamp);
            $bill_list->push($week_bill);
        }
        return $bill_list;
    }

    public function weekBill($master_id,$start_time)
    {
        $model = MasterStatisticWeek::where([
            'master_id'=>$master_id,
            'start_time'=>$start_time,
        ])->first();
        if (!$model){
            $end_time = $start_time+86400*7;
            $order_count = OrderOffer::where([
                "master_id"=>$master_id,"status"=>Params::OFFER_STATUS_EMPLOYED
            ])->where('add_time','>=',$start_time)->where('add_time','<',$end_time)->count();
            $income_sum = MasterTradeLog::where([
                'master_id'=>$master_id,"type"=>Params::TRADE_TYPE_ORDER,'status'=>Params::TRADE_STATUS_SUCCESS
            ])->where('add_time','>=',$start_time)->where('add_time','<',$end_time)->sum('amount');
            $model = MasterStatisticWeek::create([
                'master_id'=>$master_id,
                'start_time'=>$start_time,
                'end_time'=>$end_time,
                'order_count'=>$order_count,
                'income_sum'=>$income_sum,
            ]);
        }
        return $model;
    }

    public function billDetailList($master_id, $start_time)
    {
        $end_time = $start_time+86400*7;
        $order_ids = OrderOffer::where([
            "master_id"=>$master_id,"status"=>Params::OFFER_STATUS_EMPLOYED
        ])->where('add_time','>=',$start_time)->where('add_time','<',$end_time)->get()->pluck('order_id');
        if (empty($order_ids)){
            return [];
        }
        return Order::whereIn('id',$order_ids)->orderBy('add_time','DESC')->get();
    }


}